package com.dai.yygh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dai.yygh.model.hosp.Department;
import com.dai.yygh.repository.DepartmentRepository;
import com.dai.yygh.service.DepartmentService;
import com.dai.yygh.vo.hosp.DepartmentQueryVo;
import com.dai.yygh.vo.hosp.DepartmentVo;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.select.GroupByElement;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        //将获取到的信息转换成department对象
        Department department = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Department.class);
        Department departmentByHoscodeAndDepcode = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (departmentByHoscodeAndDepcode != null) {
            departmentByHoscodeAndDepcode.setUpdateTime(new Date());
            departmentByHoscodeAndDepcode.setIsDeleted(0);
            departmentRepository.save(departmentByHoscodeAndDepcode);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }


    @Override
    public Page<Department> selectPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
            Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
            //0为第一页
            Pageable pageable = PageRequest.of(page - 1, limit, sort);

            Department department = new Department();
            BeanUtils.copyProperties(departmentQueryVo, department);
            department.setIsDeleted(0);

            //创建匹配器，即如何使用查询条件
            ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                    .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                    .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写//创建实例
            Example<Department> example = Example.of(department, matcher);
            Page<Department> pages = departmentRepository.findAll(example, pageable);


            return pages;

        }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(null != department) {
            //departmentRepository.delete(department);
            departmentRepository.deleteById(department.getId());
        }

    }

    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        // 创建Pageable对象,设置当前页和每页记录数
        PageRequest pageable = PageRequest.of(page - 1, limit);
        // 创建Example对象
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Department> example = Example.of(department, matcher);

        Page<Department> all = departmentRepository.findAll(example, pageable);
        return all;
    }

    /**
     *  根据医院编号，查询医院所有科室列表
     * @param hoscode
     * @return
     */
    @Override
    public List getDeptList(String hoscode) {
        List<DepartmentVo> departmentVoList=new ArrayList<>();

        Department department = new Department();
        department.setHoscode(hoscode);
        Example example = Example.of(department);
        List<Department> all = departmentRepository.findAll(example);

        //利用stream流进行分组
        Map<String, List<Department>> collect = all.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //遍历map
        for (Map.Entry<String,List<Department>> entry: collect.entrySet()){
            String bighoscode = entry.getKey();
            List<Department> departmentList = entry.getValue();

            //封装大科室
            DepartmentVo departmentVo1 = new DepartmentVo();
            departmentVo1.setDepcode(bighoscode);
            departmentVo1.setDepname(departmentList.get(0).getBigname());


            //封装小科室
            List<DepartmentVo> children = new ArrayList<>();
            for (Department department1 : departmentList) {
                //转换成树形进行返回 利用vo类
                DepartmentVo departmentVo = new DepartmentVo();
                departmentVo.setDepcode(department1.getDepcode());
                departmentVo.setDepname(department1.getDepname());
                children.add(departmentVo);
            }

            departmentVo1.setChildren(children);
            //放到最终result里面
            departmentVoList.add(departmentVo1);
        }
        return departmentVoList;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (department != null) {
            return department.getDepname();
        }
        return null;
    }

    @Override
    public List<Department> findTree(String hoscode) {
        return departmentRepository.findDepartmentsByHoscodeLike(hoscode);
    }
}
